package com.zjj.algorithm.learning.atguigu.algorithm;

/**
 * 非递归方式的二分查找
 *
 * @author zjj_admin
 * @date 2022/12/6 20:37
 */
public class BinarySearchNoRecur {

    public static void main(String[] args) {

        int[] arr = new int[]{-2, -1, 0, 1, 6, 9, 25, 63, 89, 236, 652, 663, 1000};
        int res = binarySearchNoRecur(arr, 1000);
        System.out.println("res = " + res);
    }

    /**
     * @param arr
     * @param val
     * @return
     */
    public static int binarySearchNoRecur(int[] arr, int val) {
        int left = 0;
        int right = arr.length - 1;
        int mid;
        while (left <= right) {
            mid = (left + right) / 2;
            if (arr[mid] == val) {
                return mid;
            } else if (arr[mid] > val) {
                //当中间值大于查找值时，将右指针左移
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return -1;
    }
}
